
const socketio = {}
const socket = require("socket.io");
const { chatModel } = require('./model/model')
socketio.getScoketio = function (server) {
  const io = socket(server, {
    cors: true
  });
  let userList = []
  io.on('connection', async (sock) => {
    console.log("连接成功。.")
    console.log('a user connected')
    sock.emit("connectionSuccess"); //向客户端发送连接成功的消息
    sock.on("joinRoom", (roomId) => {
      sock.join(roomId);//房间加入到服务端
    })
    //监听向房间发送视频
    sock.on("callRemote", (roomId) => {
      //信令服务器向其他人广播这个事件
      io.to(roomId).emit("callRemote");//这个房间所有人都会收到视频请求的邀请
    })
    //处理一下同意视频请求acceptCall事件
    sock.on("acceptCall", (roomId) => {
      //信令服务器通知用户A 同意视频请求 向房间广播了这个事件
      io.to(roomId).emit("acceptCall");
    })
    //接收offer
    sock.on("sendOffer", ({ offer, roomId }) => {
      io.to(roomId).emit("sendOffer", offer);
    })
    //接收answer
    sock.on("sendAnswer", ({ answer, roomId }) => {
      io.to(roomId).emit("sendAnswer", answer);
    })
    // 收到candicate信息
    sock.on("sendCandidate", ({ candidate, roomId }) => {
      io.to(roomId).emit("sendCandidate", candidate);
    })
    // 挂断
    sock.on("hangUp", (roomId) => {
      io.to(roomId).emit("hangUp");
    })








    const username = sock.handshake.query.username
    const elename = sock.handshake.query.elename
    if (!username) {
      return
    }
    const userinfo = userList.find((ele) => ele.username === username)
    if (userinfo) {
      //存在
      userinfo.id = sock.id
    } else {
      userList.push({
        id: sock.id,
        username,
        
      })
    }
    //发送事件
    io.emit('userList', userList)
    let chatlist = await chatModel.find({ $and: [{ rightName: username }, { leftName: elename }] })
    io.emit('list', chatlist)

    //监听接收消息的对象
    sock.on('sendMessage', async (data) => {
      let chatlist = await chatModel.find()
      let rightlist = chatlist.filter(ele => ele.rightId === data.rightId && ele.leftId === data.leftId)
      if (rightlist.length) {
        let _id = rightlist[0]._id
        let arr = rightlist[0].chatContent
        arr.push({
          val: data.rightVal,
          time: data.time,
          status: true
        })
        await chatModel.updateOne({ _id }, { chatContent: arr })
      }
      let leftlist = chatlist.filter(ele => ele.rightId === data.leftId && ele.leftId === data.rightId)
      if (leftlist.length) {

        let _id = leftlist[0]._id
        let arr = leftlist[0].chatContent
        arr.push({
          val: data.rightVal,
          time: data.time,
          status: false
        })
        await chatModel.updateOne({ _id }, { chatContent: arr })
      }
      const targetSocket = io.sockets.sockets.get(data.id)
      if (targetSocket) {
        targetSocket.emit('chatList', rightlist)
      }
    })
    //监听断开连接的信息
    sock.on('close', (username) => {
      userList = userList.filter((user) => user.username !== username)
      console.log(userList)
      io.emit('userList', userList)
    })
    sock.on('disconnect', () => {
      console.log('user disconnected')
    })



















  });
}
module.exports = socketio;